<?php
class Admin_UsersController extends Zend_Controller_Action
{
    protected $_flashMessenger = null;

    public function init()
    {
        $this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $this->initView();
    }

	function listAction()
	{
		$users = Doctrine_Query::create()
            ->select('u.name, u.login, u.email, g.name')
            ->from('User u')
            ->leftJoin('u.groups g')
            ->setHydrationMode(Doctrine::HYDRATE_ARRAY)
            ->execute();

        $this->view->users = $users;
	}

    function addAction()
    {
        $form = new UserForm();
        $form->submit->setLabel('Add');

        $pairs = Doctrine::getTable('Group')->fetchPairs('id', 'name');
        $groupSelect = $form->getElement('group_id');
        $groupSelect->addMultioptions($pairs);

        $this->view->form = $form;

        if($this->_request->isPost())
        {
        	$formData = $this->_request->getPost();
        	if($form->isValid($formData))
        	{
                $filtered_data = $form->getValues(true);

                $user = new User();
                $user->merge($filtered_data);
                $user->password = (hash('MD5', $filtered_data['password']));
        		$user->save();

        		$groups = $form->getValue('group_id');

        		foreach($groups as $group)
        		{
                    $user_group = new UserGroup();
                    $user_group->user_id = $user->id;
                    $user_group->group_id = $group;
                    $user_group->save();
        		}

        		$this->_flashMessenger->addMessage('User created!');
        		$this->_helper->redirector('index');
        	}
        	else
        	{
        		$form->populate($formData);
        	}
        }// if isPost
    }

    function editAction()
    {
        $form = new UserForm();
        $form->submit->setLabel('Save');

        $groups = Doctrine_Query::create()
            ->from('Group g')
            ->select('g.id, g.name, g.description')
            ->setHydrationMode(Doctrine::HYDRATE_ARRAY)
            ->execute();

        $group_id = $form->getElement('group_id');

        foreach($groups as $group)
            $group_id->addMultiOption($group['id'], $group['name'].' ('.$group['description'].')');

        $this->view->form = $form;

        $user = $this->_findRecord();

        if($this->_request->isPost())
        {
            $formData = $this->_request->getPost();
            if($form->isValid($formData))
            {
            	$filtered_data = $form->getValues(true);

                $user->merge($filtered_data);
                $user->password = (hash('MD5', $filtered_data['password']));
                $user->save();

                $user->unlink('groups');
                $groups = $form->getValue('group_id');

                foreach($groups as $group)
                {
                    $user_group = new UserGroup();
                    $user_group->user_id = $user->id;
                    $user_group->group_id = $group;
                    $user_group->save();
                }

                $this->_flashMessenger->addMessage('User updated!');
                $this->_helper->redirector('index');
            }
            else
            {
                $form->populate($formData);
            }
        }
        else
        {
     		$form->populate($user->toArray());
            $group_id->setValue($user->groups->getPrimaryKeys());
        }
    }

    function deleteAction()
    {
        $user = $this->_findRecord();

        if($this->_request->isPost())
        {
        	$del = $this->_request->getPost('del');
        	if ($del == 'Yes')
        	{
        		$user->unlink('groups');
        		$user->delete();

        		$this->_flashMessenger->addMessage('User deleted!');
        	}

        	$this->_helper->redirector('index');
        }
        else
        {
      		$this->view->user = $user;
        }
    }

    function indexAction()
    {
        $this->view->groupSelect = Doctrine::getTable('Group')->createSelect(false);
        $this->view->flash = $this->_flashMessenger->getMessages();
    }

    function ajaxFetchUsersAction()
    {
        $params = array(
            'offset'    => $this->_request->getParam('start', 0),
            'limit'     => $this->_request->getParam('limit', 20),
            'sort'      => $this->_request->getParam('sort', 'id'),
            'dir'       => $this->_request->getParam('dir', 'ASC'),
            'group_id'  => $this->_request->getParam('group_id', 0),
        );

        $rawData = Doctrine::getTable('User')->fetchExtGridData($params);
        $this->_helper->json($rawData);

//        $json = Zend_Json_Encoder::encode($rawData);
//
//        $this->_helper->layout->disableLayout();
//        $this->_helper->viewRenderer->setNoRender();
//
//        $this->_response->setHeader('Content-Type', 'text/javascript');
//        $this->_response->appendBody($json);
    }
    
    /**
     * Finds record in database
     * 
     * @return Doctrine_Record
     */
    protected function _findRecord()
    {
        $id = (int) $this->_request->getParam('id');
        $record = Doctrine::getTable('User')->find($id);
        if (!$record) throw new Zend_Controller_Dispatcher_Exception();

        return $record;
    }  
}
?>